package com.weblog.home.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weblog.home.client.ArticleSearchClient;
import com.weblog.home.client.CategoryClient;
import com.weblog.home.client.CommentClient;
import com.weblog.home.client.UserClient;
import com.weblog.model.article.output.CategoryVo;
import com.weblog.model.home.HomeChartVO;
import com.weblog.model.home.ModuleCountVo;
import entity.Result;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import util.MapSizeUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author MaoLin Wang
 * @date 2019/10/317:53
 */
@Service
public class HomeService {

    @Autowired
    private ArticleSearchClient articleSearchClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private CommentClient commentClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private MapSizeUtil mapSizeUtil;

    @Autowired
    private RedisTemplate jsonRedisTemplate;


    private static final String PREFIX_KEY = "level_statis";

    /**
     * 加了缓存 尚未测试！
     * TODO 待测试
     * @param level
     * @return
     */
//    @Scheduled(cron = "0 0 0 * * ? *")
    public List<HomeChartVO> fetchDataInfo(int level) {
        //最终返回结果集合
        List<HomeChartVO> resultList = new ArrayList<>();
        HomeChartVO result = (HomeChartVO) jsonRedisTemplate.opsForHash().get(PREFIX_KEY, "lev" + level);
        if (result != null) {
            resultList.add(result);
            return resultList;
        }
        //通过分类等级查询分类id和分类名结合
        Result cidResult = categoryClient.findCidsAndCnamesByClevel(level);
        CategoryVo map = null;
        if (cidResult.isFlag()) {
            ObjectMapper objectMapper=new ObjectMapper();
            map = objectMapper.convertValue(cidResult.getData(), CategoryVo.class);
//            map = (CategoryVo) cidResult.getData();
        }else {
            return null;
        }
        //分类id集合
        List<String> cidList = map.getCids();
        //调用搜索微服务接口，获取各分类文章数量
        Result countResult = articleSearchClient.fetchTotalByCategory(level, cidList);
        if (!countResult.isFlag()) {
            System.out.println("主页微服务-----调用搜索微服务出错----------");
        }
        //各分类对应的文章数量集合和各分类对应的文章id集合
        //articleCountList:List<Long>countList
        //aidsMap: Map<String, Object> aidsResultMap; key:cid value:List<String>aids
        Map<String, Object> resultData = (Map<String, Object>) countResult.getData();
        //各分类文章数量集合
        List<Long> articleCountList = null;
        if (ObjectUtils.allNotNull(resultData)) {

            articleCountList = (List<Long>) resultData.get("articleCountList");
        }

        // articleCountList= (List<Long>)articleCountList;

        //各分类文章id的map
        Map<String, Object> aidsMap = (Map<String, Object>) resultData.get("aidsMap");

        //各分类评论数量
        List<Long> commentCountList = new ArrayList<>();
        for (String cid : cidList) {
            List<String> aids = (List<String>) aidsMap.get(cid);
            if (aids == null) {
                commentCountList.add(0L);
            } else {
                Long count = Integer.valueOf((Integer) commentClient.countCommentByAids(aids).getData()).longValue();
                commentCountList.add(count);
            }
        }


        //分类名集合
        List<String> cnames = map.getCnames();
        /**
         * 封装结果集
         */
        HomeChartVO vo = new HomeChartVO();
        vo.setXData(cnames);
        vo.setAreaArticleData(articleCountList);
        vo.setAreaCommentData(commentCountList);
        jsonRedisTemplate.opsForHash().put(PREFIX_KEY, "lev" + level, vo);
        jsonRedisTemplate.expire(PREFIX_KEY, 12, TimeUnit.HOURS);
        resultList.add(vo);

        return resultList;
    }

    /**
     * 统计各模块总记录数
     *
     * @return
     */
    @Scheduled(cron = "0 0 0 * * ? *")
    public ModuleCountVo count() {


        Object userResu = userClient.count().getData();

        Object categoryResu = categoryClient.countTotal().getData();
        Object articleSearchResu = articleSearchClient.getSum().getData();
        Object commentResu = commentClient.countTotal().getData();
        if (ObjectUtils.allNotNull(userResu, categoryResu, articleSearchResu, commentResu)) {

            long userCount = Integer.valueOf((Integer) userResu).longValue();

            long categoryCount = Integer.valueOf((Integer) categoryResu).longValue();

            long articleCount = Integer.valueOf((Integer) articleSearchResu).longValue();

            long commentCount = Integer.valueOf((Integer) commentResu).longValue();

            ModuleCountVo vo=new ModuleCountVo();
            vo.setArticleCount(articleCount);
            vo.setUserCount(userCount);
            vo.setCategoryCount(categoryCount);
            vo.setCommentCount(commentCount);
            return vo;
        }
        return null;


    }

    /**
     * 获取热门文章列表
     *
     * @return
     */
    @Scheduled(cron = "0 0 0 * * ? *")
    public Map<String, Object> fetchHot20() {
        Result result = articleSearchClient.fetchHotArticle();
        Map<String, Object> map = (Map<String, Object>) result.getData();
        return map;
    }


}
